package com.hongfeng.support.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.hongfeng.support.item.ParmItem;
import com.hongfeng.support.item.tag.FieldOperator;
import com.hongfeng.support.model.Purview;
import com.hongfeng.support.model.Role;
import com.hongfeng.support.model.User;
import com.hongfeng.support.service.PurviewService;
import com.hongfeng.support.service.RoleService;
import com.hongfeng.support.service.UserService;
import com.hongfeng.support.service.common.impl.GenericServiceImpl;

@Service
public class RoleServiceImpl extends GenericServiceImpl<Role, Long> implements
		RoleService {

	@Resource
	private UserService userService;
	@Resource
	private PurviewService purviewService;

	public RoleServiceImpl() {
		super(Role.class);
	}

	/**
	 * 删除与角色有关联的外键,比如:账户信息 但这里要添加到事务控制,在application-context.xml里面用声明式事务控制,还未加.
	 * 
	 */
	public void deleteRoleWithRelation(String ids) throws Exception {
		String[] idArr = ids.split(",");
		for (String idStr : idArr) {
			Long id = Long.parseLong(idStr);
			ParmItem item = new ParmItem("role.id", id, FieldOperator.EQUAL);
			List<User> users = userService.findAllByQuery(User.class, item);
			for (User u : users) {
				u.setRole(null);
				userService.update(u);
			}

			List<Purview> purviews = purviewService.findAllByQuery(
					Purview.class, item);
			for (Purview purview : purviews) {
				purviewService.delete(purview.getId());
			}
			this.delete(id);
		}
	}

}
